<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <NSpace>
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules"
                :label-width="115" :model="formValue" style="width: 1000rem" label-align="right">
                <NFormItem>
                  <div class="progress">
                    <div style="display:flex; width: auto;padding: 0 15px;">
                      <NIcon :size="20" class="iconStyle">
                        <ApprovalFilled />
                      </NIcon>
                      <span>审批流程</span>
                    </div>
                    <span style="font-size: 18rem;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                      {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
                    </span>
                  </div>
                </NFormItem>

                <NSpace justify="space-between">
                  <NFormItem label="申请类型:" path="receptionType">
                    <n-radio-group v-model:value="formValue.receptionType" name="radiogroup">
                      <NSpace justify="space-between">
                        <n-radio value="A4301" style="margin-right: 50rem">
                          接待申请
                        </n-radio>
                        <n-radio value="A4302">接待计划</n-radio>
                      </NSpace>
                    </n-radio-group>
                  </NFormItem>
                  <NFormItem label="访问时间:" path="accessTime">
                    <NDatePicker input-readonly placeholder="请选择访问时间" class="commonWidth"
                      v-model:formatted-value="formValue.accessTime" clearable />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="访问单位/个人:" path="accessMan">
                    <NInput placeholder="请输入访问单位/个人" class="commonWidth" v-model:value="formValue.accessMan"
                      clearable />
                  </NFormItem>
                  <NFormItem label="带队领导/职务:" path="duty">
                    <NInput placeholder="请输入带队领导/职务" class="commonWidth" v-model:value="formValue.duty" clearable />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="接待级别:" path="receptionLevel">
                    <NSelect placeholder="请输入访问单位/个人" class="commonWidth" v-model:value="formValue.receptionLevel"
                      clearable :options="parentCodeList" value-field="dicCode" label-field="dicName" />
                  </NFormItem>
                  <NFormItem label="参观人数:" path="accessNum">
                    <NInput placeholder="请输入参观人数" class="commonWidth" v-model:value="formValue.accessNum" clearable
                      :allow-input="onlyAllowNumber" />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="联系人姓名:" path="contacts">
                    <NInput placeholder="请输入联系人姓名" class="commonWidth" v-model:value="formValue.contacts" clearable />
                  </NFormItem>
                  <NFormItem label="联系人联系方式:" path="phone">
                    <NInput placeholder="请输入联系人联系方式" class="commonWidth" v-model:value="formValue.phone" clearable />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="联系人身份证号:" path="idCard">
                    <NInput placeholder="请输入联系人身份证号" class="commonWidth" v-model:value="formValue.idCard" clearable />
                  </NFormItem>
                  <NFormItem label="访问地点:" path="accessPlace">
                    <NInput placeholder="请输入访问地点" class="commonWidth" v-model:value="formValue.accessPlace" clearable />
                  </NFormItem>
                </NSpace>

                <NSpace justify="space-between">
                  <NFormItem label="访问事由:" path="reasons">
                    <NInput placeholder="请输入访问事由" class="commonWidth" v-model:value="formValue.reasons" clearable />
                  </NFormItem>
                  <NFormItem label="访问车辆车牌:" path="licensePlate">
                    <NInput placeholder="请输入访问车辆车牌" class="commonWidth" v-model:value="formValue.licensePlate"
                      clearable />
                  </NFormItem>
                </NSpace>

                <NSpace style="display: flex; flex-direction: column">
                  <NFormItem label="同行人员:" path="scopeOrPeopleList">
                    <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost
                      @click="modalVisible = true">
                      点击设置查看
                    </NButton>
                  </NFormItem>
                </NSpace>

                <NFormItem label="附件:">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>
              </NForm>
            </NSpace>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(1)" :loading="loading"
          v-if="formValue.entityId">
          保存草稿
        </NButton>
        <NButton type="primary"  @click="confirm(0)" :loading="loading" v-if="formValue.entityId">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <ModalCard @close="modalVisible = false">
      <div style="padding: 0 0 20rem 0">
        <VStaffAdd @close="modalVisible = false" @submit="getStaffList" :defaultList="formValue.receptionInfoList"
          :flat="true" />
      </div>
    </ModalCard>
  </NModal>
</template>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NSelect,
  NButton,
  NScrollbar,
  NModal,
  useMessage,
  NSpin,
  NDatePicker,
  NRadioGroup,
  NRadio,
  NIcon,
  NImage,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { onMounted } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { ReceptionModel } from '@/api/reception'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VStaffAdd from './staffAdd.vue'
import ModalCard from '@/components/ModalCard.vue'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
  title: { type: String, default: () => '接待申请' },
  id: { type: [Number, String], default: () => null },
  flat: { default: () => false }
})
const message = useMessage()
const modalVisible = ref(false)

const formValue = reactive<Record<string, any>>({
  accessTime: null, //访问时间
  accessMan: null, //访问单位/个人
  receptionType: null, //类型
  duty: null, //带队领导/职务
  receptionLevel: null, //接待级别
  accessNum: null, //参观人数
  contacts: null, //联系人姓名
  phone: null, //联系人联系方式
  idCard: null, //联系人身份证号
  accessPlace: null, //访问地点
  reasons: null, //访问事由
  licensePlate: null, //访问车辆车牌
  fileId: null, //附件
  draft: null, //草稿状态
  entityId: null, //流程实体id
  receptionInfoList: null //同行人员
})
const rules: any = {
  idCard: {
    required: false,
    validator: (_: any, value: any) => {
      if (!value) return true
      let regu = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
      return regu.test(value)
    },
    trigger: ['input', 'blur'],
    message: '请输入联系人身份证号'
  },
  contacts: {
    required: true,
    message: '请输入联系人姓名',
    trigger: ['input', 'blur']
  },
  phone: {
    required: false,
    message: '请输入联系人联系方式',
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return true
      let regu = /^1[3-9][0-9]{9}$/
      return regu.test(value)
    }
  },
  receptionType: {
    required: true,
    message: '请选择类型',
    trigger: ['select', 'change']
  },
  accessTime: {
    required: true,
    type: 'any',
    message: '请选择访问时间',
    trigger: ['select', 'change']
  }
}
// 人员列表
const getStaffList = (v: any) => {
  formValue.receptionInfoList = v
  modalVisible.value = false
}
// 类型
const parentCodeList: any = ref()
const getParentCode = async () => {
  const [error, res] = await sendRequest<HttpResponse<ReceptionModel>>({
    module: 'receiveOrDispatch',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A44'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  parentCodeList.value = res.data
}
// 获取流程id
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse<ReceptionModel>>({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: 'A0536'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  spinShow.value = false
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 附件
const handleUploadList = (v: any) => (formValue.fileId = v)
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const contentContent = ref()
const confirm = (status: number) => {
  formRef.value?.validate(async (err) => {
    if (err) return (contentVisible.value = false)
    if (!formValue.receptionInfoList?.length)
      return message.error('请选择同行人员'), (contentVisible.value = false)
    formValue.draft = status
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    contentVisible.value = true
  })
}
// 提交
const contentVisible = ref(false)
const submit = async () => {
  if ((props.id && props.flat) || (!props.id && !props.flat)) {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<ReceptionModel>>({
      module: 'reception',
      api: 'receptionAdd',
      override: {
        data: formValue
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  } else {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<ReceptionModel>>({
      module: 'reception',
      api: 'receptionUpdate',
      override: {
        data: {
          ...formValue,
          id: props.id
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  }
  goSubmit()
}


//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
 tags.splice(index, 1)
  if(formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}


// 获取修改详情
const fileList: any = ref([])
const getReceptionInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<ReceptionModel>>({
    module: 'reception',
    api: 'receptionInfo',
    uri: {
      id: props.id
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    if (it == 'accessTime') return (formValue[it] = res.data[it].split(' ')[0])
    // @ts-ignore
    formValue[it] = res.data[it]
  })
}
// 只允许输入数字
const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value)

// watch(
//   () => route,
//   async () => {
//     if (route.path == '/OA/Reception/ReceptionUpdate' && props.title == '接待编辑' && props.id) {
//       await getReceptionInfo()
//       await getWorkFlow()
//     }
//     if (route.path == '/OA/Reception/ReceptionAdd' && props.title == '接待申请') getWorkFlow()
//   },
//   { deep: true, immediate: true }
// )
watch(
  () => props.id,
  () => {
    if (props.title == '接待编辑' && props.id) getReceptionInfo()
  },
  { deep: true, immediate: true }
)
onMounted(async () => {
  getParentCode()
  getWorkFlow()
})
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: auto;
        min-height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  width: 100%;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  padding: 10rem;
  display: flex;
  align-items: center;
  margin-top: 10rem;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

// :deep(.n-scrollbar-content) {
//   width: 100%;
//   height: 100%;
// }

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
